package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.geoaimavlink_android.R
import com.example.geoaimavlink_android.utils.DateTimeUtil
import com.geoai.mavlink.geoainet.system.enums.LoggerSystemType
import com.geoai.mavlink.geoainet.system.info.FlightLogEntryInfo
import com.geoai.mavlink.geoainet.system.interfaces.IFetchFlightLogListListener
import com.geoai.mavlink.geoainet.system.interfaces.IFlightLogDownloadListener
import com.geoai.mavlink.util.FileUtils
import kotlinx.android.synthetic.main.frag_log.btn_cancel
import kotlinx.android.synthetic.main.frag_log.btn_download
import kotlinx.android.synthetic.main.frag_log.btn_module_select
import kotlinx.android.synthetic.main.frag_log.btn_refresh
import kotlinx.android.synthetic.main.frag_log.edt_index
import kotlinx.android.synthetic.main.frag_log.rcy
import kotlinx.android.synthetic.main.frag_log.tv_sync
import kotlinx.android.synthetic.main.fragment_play.progress
import java.io.File

class LogFragment: BaseFragment() {

    private var mLoggerType: LoggerSystemType = LoggerSystemType.FC

    private val mLoggerLists = mutableListOf<FlightLogEntryInfo>()

    private val logRecycleAdapter = LogRecycleAdapter(mLoggerLists)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_log, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initRecycleView()
    }

    private fun initView() {
        btn_module_select.setOnClickListener {
            mLoggerType = when(mLoggerType) {
                LoggerSystemType.FC -> LoggerSystemType.CREST
                LoggerSystemType.CREST -> LoggerSystemType.CAMERA
                LoggerSystemType.CAMERA -> LoggerSystemType.FC
            }
            btn_module_select.text = mLoggerType.name
        }

        btn_refresh.setOnClickListener {
            mLoggerLists.clear()
            logRecycleAdapter.notifyDataSetChanged()

            getProduct()?.systemManager?.fetchFlightLogList(mLoggerType, object : IFetchFlightLogListListener {
                override fun onSync(percentage: Float) {
                    mainHandler.post { tv_sync.text = percentage.toString() }
                }

                override fun onResult(
                    isSuccess: Boolean,
                    infoList: MutableList<FlightLogEntryInfo>?
                ) {
                    showToast("$isSuccess ${infoList?.size}")
                    if (isSuccess) {
                        infoList?.forEach {
                            mLoggerLists.add(it)
                        }
                    }
                    logRecycleAdapter.notifyDataSetChanged()
                }

                override fun onTotalLogCount(count: Int) {
                    Log.i("Ronny", "count: " + count);
                }
            })
        }

        btn_cancel.setOnClickListener {
            getProduct()?.systemManager?.cancelFetchFlightLog()
        }

        btn_download.setOnClickListener {
            val downloadIndex = edt_index.text.toString().toInt()
            val downloadItem = mLoggerLists.firstOrNull { it.id == downloadIndex }
            downloadItem?.let {
                val savePath = requireActivity().externalCacheDir!!.path + File.separator
                getProduct()?.systemManager?.fetchFlightLog(mLoggerType, downloadItem, savePath, "log_" + downloadItem.timestamp, object : IFlightLogDownloadListener {
                    override fun onProcess(currentDownloadSize: Long, fileTotalSize: Long) {
                        mainHandler.post {
                            tv_sync?.text = "current: $currentDownloadSize \r\n" +
                                "total:$fileTotalSize \r\n" +
                                "percent:${(currentDownloadSize.toDouble() / fileTotalSize * 100).toInt()}" }
                    }

                    override fun onResult(isSuccess: Boolean, errCode: Int) {
                        showToast("ret:$isSuccess ${errCode}::${"log_" + downloadItem.timestamp}")
                        Log.i("Ronny", "ret:$isSuccess ${errCode}")
                    }
                })
            }
        }
    }

    private fun initRecycleView() {
        rcy.layoutManager = LinearLayoutManager(requireContext())
        rcy.adapter = logRecycleAdapter
    }

    class LogRecycleAdapter(private val infoList: MutableList<FlightLogEntryInfo>?) : RecyclerView.Adapter<LogRecycleAdapter.VH>() {

        class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val tvIndex: TextView = itemView.findViewById(R.id.tv_index)
            val tvTs: TextView = itemView.findViewById(R.id.tv_ts)
            val tvSize: TextView = itemView.findViewById(R.id.tv_size)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
            return VH(LayoutInflater.from(parent.context).inflate(R.layout.item_log_recycle, parent, false))
        }

        override fun getItemCount() = infoList?.size?:0

        override fun onBindViewHolder(holder: VH, position: Int) {
            infoList?.get(position)?.timestamp?.let { ts ->
                holder.tvTs.text = DateTimeUtil.getInstance().formatDateTime((ts * 1000), 0)
            }
            infoList?.get(position)?.size?.let { size ->
                holder.tvSize.text = FileUtils.getFileSzie(size)
            }
            holder.tvIndex.text = infoList?.get(position)?.id?.toString()?:"-1"
        }
    }
}